const path = require('path')
const fs = require('fs');
const {
    promisify
} = require('util')
const rename = promisify(fs.rename)
const articleController = {};
const moment = require('moment')
const viewsDir = path.join(path.dirname(__dirname), 'views')
// query.js连接数据库
const query = require('../model/query.js')
articleController.index = (req, res) => {
    res.render(`article.html`)
}
// 查询文章表
articleController.artData = async (req, res) => {
    const {
        page,
        limit,
        keyword
    } = req.query;
    let sql1 = `select count(id) as count from article where 1 `;
    if (keyword) {
        sql1 += ` and title like '%${keyword}%' `
    }
    const result = await query(sql1)
    const {
        count
    } = result[0]
    const offset = (page - 1) * limit;
    let sql2 = `select t1.*,t2.cate_name,t3.username from article t1 
        left join category t2 on t1.cate_id = t2.cate_id 
        left join users t3 on t1.author = t3.id 
        where 1 `

    if (keyword) {
        sql2 += ` and t1.title like '%${keyword}%'`;
    }

    sql2 += `order by t1.id asc
    limit ${offset},${limit}`

    let data = await query(sql2)
    data = data.map((item) => {
        const {
            add_date,
            status,
            cate_name,
            username
        } = item;
        item.statusText = status == 1 ? '审核通过' : "审核失败"
        item.cate_name = cate_name || '未分类'
        item.username = username || '未知'
        item.add_date = moment().format('YYYY-MM-DD')
        return item;
    })
    // 4. 响应数据
    res.json({
        count,
        data,
        code: 0,
        msg: "成功"
    })
}

// 删除
articleController.delArtData = async (req, res) => {
    const {
        id
    } = req.body;
    const sql = `delete from article where id = ${id}`
    const {
        affectedRows
    } = await query(sql)
    if (affectedRows > 0) {
        res.json({
            code: 0,
            message: "删除成功"
        })
    } else {
        res.json({
            code: -7,
            message: "删除失败"
        })
    }
}
// 添加
articleController.addArticle = (req, res) => {
    res.render('addArticle.html')
}
// 
articleController.addArtData = async (req, res) => {
    const {
        title,
        cate_id,
        status,
        content
    } = req.body;
    const add_date = moment().format('YYYY-MM-DD HH:mm:ss')
    const author = req.session.userInfo.id;
    let photo = '';
    if (req.file) {
        let {
            destination,
            originalname,
            filename
        } = req.file;
        let extName = originalname.substring(originalname.lastIndexOf('.'))
        let uploadDir = './uploads'
        let oldName = path.join(uploadDir, filename);
        let newName = path.join(uploadDir, filename) + extName;

        try {
            const result = await rename(oldName, newName)
            photo = `uploads/${filename}${extName}`

        } catch (err) {
            console.log('上传失败')
        }


    }
    let sql = `insert into article(title,cate_id,status,content,add_date,author,photo) 
            values('${title}','${cate_id}','${status}','${content}','${add_date}','${author}','${photo}')`
    const {
        affectedRows
    } = await query(sql)
    if (affectedRows > 0) {
        res.json({
            code: 0,
            message: '添加文章成功'
        })
    } else {
        res.json({
            code: -7,
            message: '添加文章失败'
        })
    }
}
articleController.editArt = (req, res) => {
    res.render('editArticle.html')
}

articleController.fetchOneArt = async (req, res) => {
    // 1. 接收参数
    let {
        id
    } = req.query
    // 2. 查询单条的sql语句
    const sql = `select * from article where id = ${id}`
    const result = await query(sql)
    res.json(result[0])

}

articleController.updArtData = async (req, res) => {
    //1. 接收参数
    let {
        id,
        title,
        content,
        cate_id,
        isUpdPhoto,
        status,
        oldPhoto
    } = req.body;
    //2. 是否上传文件的处理
    let photo = '';
    let sql;
    if (isUpdPhoto == 1) {
        // 上传文件
        let {
            destination,
            originalname,
            filename
        } = req.file;
        let extName = originalname.substring(originalname.lastIndexOf('.'))
        let uploadDir = './uploads'
        let oldName = path.join(uploadDir, filename);
        let newName = path.join(uploadDir, filename) + extName;

        try {
            await rename(oldName, newName)
            photo = `uploads/${filename}${extName}`
            let oldPhotoFullPath = path.join(path.dirname(__dirname), oldPhoto)
            fs.unlink(oldPhotoFullPath, (err) => {})

        } catch (err) {
            console.log('上传失败')
        }

        sql = `update article set title='${title}',content='${content}',cate_id='${cate_id}',status='${status}', photo='${photo}' where id = ${id} `;

    } else {
        sql = `update article set title='${title}',content='${content}',cate_id='${cate_id}',status='${status}'  where id = ${id} `;
    }
    //3. 执行sql
    const {
        affectedRows
    } = await query(sql)
    if (affectedRows > 0) {
        res.json({
            code: 0,
            message: "更新成功"
        })
    } else {
        res.json({
            code: -9,
            message: "更新失败"
        })
    }


}
module.exports = articleController;